using System;
using System.Threading;

using NDesk.DBus;

using stefc.geo.lib;

namespace stefc.geo.platform
{

	/// <summary>
	/// Accessing GPS Sensor over gpsd via D-Bus
	/// </summary>
	internal class GPSSensor : IGPSSensor
	{
		private Connection connection;
		private int pollIntervall;
		private volatile bool stop;
	
		public GPSSensor(int pollIntervall)
		{
			this.connection = Bus.System;
			this.pollIntervall = pollIntervall;
			
			var gpsd = this.connection.GetObject<Gpsd>("org.gpsd", new ObjectPath("/org/gpsd"));
			gpsd.fix += 
				fix => 
				{
					if(this.Out_GPSFix!=null)
						this.Out_GPSFix(new Geographic(fix.latitude,fix.longitude));
				};
		}
		
		public void In_Start()
		{
			this.stop=false;
			while(!this.stop)
			{
				this.connection.Iterate();
				Thread.Sleep(1000*this.pollIntervall);
			}
		}
		
		public void In_Stop()
		{
			this.stop=true;
		}
		
		public event Action<Geographic> Out_GPSFix;

		#region D-BUS Interface for gpsd
		[Interface("org.gpsd")]
		interface Gpsd
		{
			event Action<GPSFix> fix;
		}
		
		struct GPSFix
		{
			public double time;
			public int mode;
			public double ept;
			public double latitude;
			public double longitude;
		}
		#endregion
	}
}
